<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permissions="permissionsList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @currentPage-change="currentPageChange"
               @pageSize-change="pageSizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="primary"
                   pageSize="medium"
                   icon="el-icon-document-copy"
                   plain
                   v-if="permissions.option_inherit"
                   @click="showInheritViewBox">继 承
        </el-button>
      </template>

      <template slot-scope="{row}" slot="deptId">
        <el-tag>{{row.deptName}}</el-tag>
      </template>

    </avue-crud>
    <template>
      <!--    考核指标项继承-->
      <el-dialog top="5vh" :title="`考核指标项 继承`" :visible.sync="viewInheritBox"
                 :append-to-body="true" :before-close="closeInheritViewBox" width="1200px">
        <div class="ledger">
          <el-form ref="InheritForm" :model="inheritForm" class="el-dialog__body" label-width="100px">
            <div class="ledgerTitle">基本信息</div>
            <el-row>
              <el-col :span="8">
                <el-form-item label="原年度" prop="successorYear" :rules="{required: true, message: '原年度不能为空', trigger: ['blur', 'change']}">
                  <el-date-picker placement="bottom-start"  v-model="inheritForm.successorYear" type="year" value-format="yyyy" placeholder="继承年度">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="目标年度" prop="kpiYear" :rules="{required: true, message: '目标年度不能为空', trigger: ['blur', 'change']}">
                  <el-date-picker placement="bottom-start"  v-model="inheritForm.kpiYear" type="year" value-format="yyyy" placeholder="年度">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="考核类别" prop="kpiType" :rules="{required: true, message: '考核类别不能为空', trigger: ['blur', 'change']}">
                  <el-select v-model="inheritForm.kpiType" placeholder="考核类别">
                    <el-option v-for="dict in dict.type.kpi_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-check" size="small" type="primary" @click="optionInherit">继承</el-button>
        <el-button icon="el-icon-close" size="small" @click="closeInheritViewBox">关闭</el-button>
      </span>
      </el-dialog>
    </template>
  </basic-container>
</template>

<script>
import {add, getDetail, getList, remove, update, optionInherit} from "@/api/kpi/option";
import {mapGetters} from "vuex";
import Template from "@/views/adis/base/template";

export default {
  components: {Template},
  dictTypes: ['kpi_type'],
  data() {
    return {
      form: {},
      inheritForm: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      init: {
        deptTree: [],
      },
      props: {
        label: "title",
        value: "key"
      },
      selectionList: [],
      viewInheritBox: false,
      option: {
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: false,
        index: false,
        dialogEscape: false,
        dialogClickModal: false,
        viewBtn: true,
        selection: false,
        column: [
          {
            label: "考评类别",
            prop: "kpiType",
            type: "select",
            dicUrl: "/admin/dict/type/kpi_type",
            props: {
              label: "label",
              value: "value"
            },
            dataType: "number",
            slot: true,
            search: true,
            rules: [{
              required: false,
              message: "请选择考评类别",
              trigger: "blur"
            }]
          },
          {
            type: "year",
            dataType: "string",
            label: "年度",
            prop: "kpiYear",
            format: "yyyy",
            valueFormat: "yyyy",
            required: true,
            search: true,
            rules: [{
                required: true,
                message: "请输入年度",
                trigger: "blur"
            }]
          },
          {
            label: "考评项",
            prop: "optionName",
            rules: [{
              required: true,
              message: "请输入考评项名称",
              trigger: "blur"
            }]
          },
          {
            label: "最小分值",
            prop: "optionMinValue",
            rules: [{
              required: true,
              message: "请输入最小分值",
              trigger: "blur"
            }]
          },
          {
            label: "最大分值",
            prop: "optionMaxValue",
            rules: [{
              required: true,
              message: "请输入最大分值",
              trigger: "blur"
            }]
          },
          {
            label: "排序",
            prop: "sort",
            rules: [{
              required: true,
              message: "请输入",
              trigger: "blur"
            }]
          },
          {
            label: "描述",
            prop: "optionDetail",
            type: 'textarea',
            span: 24,
            rows: 3,
            hide: false,
            html:true,
            rules: [{
              required: false,
              message: "请输入描述",
              trigger: "blur"
            }]
          }
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permissions"]),
    permissionsList() {
      return {
        addBtn: this.vaildData(this.permissions.option_add, false),
        viewBtn: this.vaildData(this.permissions.option_add, false),
        delBtn: this.vaildData(this.permissions.option_add, false),
        editBtn: this.vaildData(this.permissions.option_add, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  created() {
  },
  methods: {
    rowSave(row, done, loading) {
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    optionInherit(){
      this.$refs['InheritForm'].validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.inheritForm.kpiYear === this.inheritForm.successorYear){
            this.$message({
              type: "warning",
              message: "原年度不能等于目标年度!"
            });
            this.loading = false;
            return false;
          }
          optionInherit(this.inheritForm).then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.closeInheritViewBox();
          }, error => {
            window.console.log(error);
            this.loading = false;
          });
        } else {
          return false;
        }
      })
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentPageChange(currentPage){
      this.page.currentPage = currentPage;
    },
    pageSizeChange(pageSize){
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        data.records.forEach(record => {
          record.kpiYear = record.kpiYear.toString();
        });
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    showInheritViewBox() {
      this.viewInheritBox = true;
    },
    closeInheritViewBox() {
      this.viewInheritBox = false;
      this.$refs['InheritForm'].resetFields()
    },
  }
};
</script>

<style>
</style>
